package com.wswy.wzcx.ui.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Parcelable
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.blankj.utilcode.util.SnackbarUtils
import com.che.libcommon.api.BaseResult
import com.che.libcommon.api.ProgressDialogObserver
import com.che.libcommon.ui.BaseActivity
import com.che.libcommon.utils.RxBus
import com.che.libcommon.utils.ToastUtils
import com.facebook.common.util.UriUtil
import com.wswy.wzcx.R
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.model.wzdb.WzdbOrderInfo
import com.wswy.wzcx.module.InternalMsgCodeKt
import com.wswy.wzcx.ui.data.OrderNoNeedParam
import com.wswy.wzcx.ui.other.LayoutHelper
import com.wswy.wzcx.utils.FileUtils
import com.wzcx.orclib.CameraActivity
import java.io.File

class UpLoadActivity : BaseActivity() {
    var REQUERT_CODE_START: Int = 10000

    companion object {
        const val KEY_ORDER_NO = "key.order.no"
        const val KEY_NEED_PARAMS = "key.need_params"
        fun startUploadPage(ctx: Context, orderNo: String?, params: Array<OrderNoNeedParam>?) {
            if(params==null||orderNo==null)return
            val intent = Intent(ctx, UpLoadActivity::class.java)
            intent.putExtra(KEY_ORDER_NO, orderNo)
            intent.putExtra(KEY_NEED_PARAMS, params)
            ctx.startActivity(intent)
        }
    }

    var orderNo: String? = null
    var params: Array<OrderNoNeedParam>? = null
    var viewsInput = mutableListOf<EditText>()
    var viewsImage = mutableListOf<ImageView>()
    lateinit var tvlateUpload: TextView
    lateinit var tvOK: TextView
    lateinit var frame: FrameLayout
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_up_load)
        setSupportActionBar(findViewById(R.id.toolbar))
        findViewById<TextView>(R.id.tv_title).text = "资料补充"
        findViewById<View>(R.id.img_back).setOnClickListener { onBackPressed() }
        supportActionBar?.let {

            it.setDisplayShowTitleEnabled(false)
            it.setDisplayHomeAsUpEnabled(false)
            it.setDisplayShowHomeEnabled(true)
        }
        frame = findViewById(R.id.frame)
        tvlateUpload = findViewById(R.id.tv_late_upload)
        tvOK = findViewById(R.id.tv_ok)
        tvlateUpload.setOnClickListener {
            lateUpLoad()
        }
        tvOK.setOnClickListener {
            startUpload()
        }
        initParams()
    }

    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return super.onSupportNavigateUp()
    }
    override fun onBackPressed() {
        RxBus.getDefault().postWithCode(InternalMsgCodeKt.UPLOAD_COMPLETE_WDZD, "")
        super.onBackPressed()
    }

    private fun startUpload() {
        val map = mutableMapOf<String, Any>()
        viewsInput.map {
            val tag = it.getTag(R.id.upload_key)
            val label = it.getTag(R.id.upload_label)

            if (tag is String) {
                val text = it.text.toString()
                if (TextUtils.isEmpty(text)) {
                    ToastUtils.showText("${label}不能为空")
                    return
                } else {
                    map[tag] = text
                }
            }

        }

        viewsImage.map {
            val tag = it.getTag(R.id.upload_key)
            val requestPath = it.getTag(R.id.requert_code)
            val label = it.getTag(R.id.upload_label)
            if (tag is String && requestPath is Int && label is String) {
                val filePath = getFilePath(requestPath.toString())
                if (filePath.exists()) {
                    map[tag] = filePath
                } else {
                    ToastUtils.showText("${label}不能为空")
                    return
                }

            }
        }

        Api.get().submitNeedParams(orderNo, map)
                .subscribe(object : ProgressDialogObserver<WzdbOrderInfo?>(this, "提示", "正在上传") {
                    override fun onApiResult(t: WzdbOrderInfo?) {
                        t.let {
                            ToastUtils.showText("上传成功")
                            RxBus.getDefault().postWithCode(InternalMsgCodeKt.UPLOAD_COMPLETE_WDZD, "")
                            RxBus.getDefault().postWithCode(InternalMsgCodeKt.ORDER_STATUS_CHANGED, "")

                            finish()
                        }
                    }

                    override fun onApiError(result: BaseResult<*>?) {
                        toastErrorMsg(result)
                    }

                })
    }

    private fun lateUpLoad() {
        onBackPressed()
    }

    fun initParams() {
        orderNo = intent?.getStringExtra(KEY_ORDER_NO)
        params = intent?.getTypedArrayExtra(KEY_NEED_PARAMS)
        initViews()
    }

    private fun initViews() {
        val scrollView = ScrollView(this)
        val layout = LinearLayout(this)
        layout.orientation = LinearLayout.VERTICAL
        scrollView.addView(layout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT))
        frame.addView(scrollView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT))
        viewsImage.clear()
        viewsInput.clear()
        params?.sortWith(Comparator { o1, o2 ->
            when {
                o1?.type == "text" -> {
                    -1
                }
                o1?.type == o2.type -> 0
                else -> 1
            }
        })

        params?.map {
            val itemView = createView(it, layout)
            if (itemView != null) {
                layout.addView(itemView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT))
            }
        }

    }

    private fun createView(item: OrderNoNeedParam, parent: ViewGroup): View? {
        return when (item.type) {
            "text" -> {
                val layout = LayoutInflater.from(this).inflate(R.layout.upload_item_text, parent, false)
                layout.findViewById<TextView>(R.id.tv_label).text = item.label
                val edText = layout.findViewById<EditText>(R.id.ed_input)
                edText.hint = TextUtils.concat("请输入", item.label)
                edText.setTag(R.id.upload_key, item.key)
                edText.setTag(R.id.upload_type, item.type)
                edText.setTag(R.id.upload_label, item.label)
                viewsInput.add(edText)
                layout
            }
            "file" -> {
                val inflate = LayoutInflater.from(this).inflate(R.layout.upload_item_file, parent, false)
                val image = inflate.findViewById<ImageView>(R.id.iv_image)
                image.setOnClickListener {
                    startCameraActivity(it)
                }
                image.setTag(R.id.requert_code, REQUERT_CODE_START++)
                viewsImage.add(image)
                inflate.findViewById<TextView>(R.id.tv_label).text = item.label
                image.setTag(R.id.upload_key, item.key)
                image.setTag(R.id.upload_type, item.type)
                image.setTag(R.id.upload_label, item.label)

                inflate
            }
            else -> {
                null
            }
        }
    }

    private fun startCameraActivity(view: View) {
        val obj = view.getTag(R.id.requert_code)
        if (obj is Int) {
            val intent = Intent(this, CameraActivity::class.java)
            intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, getFilePath(obj.toString()).absolutePath)
            intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                    CameraActivity.CONTENT_TYPE_GENERAL)
            startActivityForResult(intent, obj)
        } else {
            ToastUtils.showText("obj not is Int kotlin")
        }

    }

    private fun getFilePath(name: String): File {
        val newName = TextUtils.concat(name, ".jpg").toString()
        return FileUtils.getSaveFile(this, newName)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            viewsImage.map {
                val obj = it.getTag(R.id.requert_code)
                if (obj is Int && obj == requestCode) {
                    it.setImageURI(UriUtil.parseUriOrNull("file://" + getFilePath(obj.toString())))
                    return@map
                }

            }
        }
    }
}

inline fun <reified T : Parcelable> Intent.getTypedArrayExtra(key: String): Array<T> {
    val extra = getParcelableArrayExtra(key)
    return Array(extra.size) { extra[it] as T }
}
